package com.xiyeqilai;


import com.xiyeqilai.pojo.WebData;
import lombok.Data;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Data
public class POItoExcel {
    public static void toExcel(List<WebData> list) throws IOException {
        //新建文档
        XSSFWorkbook workbook = new XSSFWorkbook();

        //创建表
        XSSFSheet sheet = workbook.createSheet();

        //定义一个行计数器
        int rowCount = 0;
        //表头（第一行）
        XSSFRow row = sheet.createRow(rowCount++);
        //定义第一行单元格
        XSSFCell cell1 = row.createCell(0);
        cell1.setCellValue("文章图片路径");
        XSSFCell cell2 = row.createCell(1);
        cell2.setCellValue("文章标题");
        XSSFCell cell3 = row.createCell(2);
        cell3.setCellValue("浏览数");
        XSSFCell cell4 = row.createCell(3);
        cell4.setCellValue("发表日期");

        //遍历数据，将数据填入表中
        for (WebData webData : list) {
            //创建行
            XSSFRow row1 = sheet.createRow(rowCount++);

            //创建单元格
            XSSFCell cell5 = row1.createCell(0);
            XSSFCell cell6 = row1.createCell(1);
            XSSFCell cell7 = row1.createCell(2);
            XSSFCell cell8 = row1.createCell(3);
            //在单元格写入数据
            cell5.setCellValue(webData.getImg());
            cell6.setCellValue(webData.getTitle());
            cell7.setCellValue(webData.getViewCount());
            cell8.setCellValue(webData.getTime());
        }
        //获取当前时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm:ss");
        String day = simpleDateFormat.format(date);
        String time = simpleDateFormat1.format(date).replace(":", "-");
        //拼接文件路径和文件名
        String path = "D:\\xlsxData\\"+day+"\\"+time+".xlsx";
        File file = new File(path);
        //若当天第一次爬取数据，则创建一个当前日期的文件夹
        if (!file.getParentFile().exists()) {
            boolean mkdirs = file.getParentFile().mkdirs();
            if (!mkdirs){
                throw new RuntimeException("创建文件夹失败");
            }
        }
        //写入文件
        workbook.write(new FileOutputStream((file)));
        //关闭
        workbook.close();
        //提示信息
        System.out.println("创建excel完毕");
        System.out.println("文件存储为："+path);
    }
}
